<template>
  <el-dialog
    v-el-drag-dialog
    title="积分合并"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="130px">
      <el-form-item label="客户电话:" prop="targetCsmPhone">
        <el-input v-model.trim="temp.targetCsmPhone" style="width: 230px;" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="被合并客户电话:" prop="sourceCsmPhone">
        <el-input v-model.trim="temp.sourceCsmPhone" style="width: 225px;" placeholder="请输入" clearable />
        <el-button type="primary" style="margin-left: 35px;" @click="searchCsm">查询</el-button>
      </el-form-item>
      <el-form-item label="客户名称:" prop="targetCsmName">
        <el-input v-model.trim="temp.targetCsmName" disabled />
      </el-form-item>
      <el-form-item label="被合并客户名称:" prop="sourceCsmName">
        <el-input v-model="temp.sourceCsmName" disabled />
      </el-form-item>
      <el-form-item label="合并积分:" prop="score">
        <el-input-number v-model="temp.score" :controls="false" :max="999999" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="被合并客户积分:" prop="sourceCsmScore">
        <el-input-number v-model="temp.sourceCsmScore" :controls="false" style="width: 100%;" disabled />
      </el-form-item>
      <el-form-item label="备注:" prop="remark" class="block">
        <el-input v-model.trim="temp.remark" type="textarea" :rows="3" maxlength="200" show-word-limit />
      </el-form-item>
      <el-form-item label="操作步骤:" class="tip block">
        <p>1、输入客户电话号码和被合并客户电话号码，点击查询。</p>
        <p>2、在主账号客户信息列表和被合并客户信息列表中分别选择客户和被合并客户。</p>
        <p>3、修改并确认合并积分数，在输入备注信息后，点击合并按钮完成两个账户的积分合并。</p>
      </el-form-item>
    </el-form>
    <div class="info-title" style="margin-top: 0;">
      <span class="title-icon" />
      <span>主账号客户信息</span>
    </div>
    <lb-table
      ref="lbTableMain"
      border
      max-height="200"
      highlight-current-row
      :column="column1"
      :data="targetCsmList"
      :pagination="false"
      table-key="csmId"
      @row-click="toggleSelection"
      @selection-change="handleCurrentChangeOne"
      @expand-change="(row, expandedRows) => clickExpand(row, expandedRows, 1)"
    />
    <div class="info-title">
      <span class="title-icon" />
      <span>被合并客户信息</span>
    </div>
    <lb-table
      ref="lbTable"
      border
      :column="column2"
      highlight-current-row
      :data="sourceCsmList"
      :pagination="false"
      max-height="200"
      table-key="csmId"
      @selection-change="handleCurrentChangeTwo"
      @row-click="toggleSelection2"
      @expand-change="(row, expandedRows) => clickExpand(row, expandedRows, 2)"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="merge">
        合并
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryCsmByPhone, mergeScore, queryCsmInfo } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  const newFromMap = {
    0: '户外广告',
    1: '销售人员推广',
    2: '户外广告',
    3: '互联网媒体',
    4: '朋友介绍',
    5: '微信推广'
  }

  export default {
    name: 'merge',
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        temp: {
          targetCsmPhone: '',
          sourceCsmPhone: '',
          targetCsmName: '',
          sourceCsmName: '',
          score: undefined,
          sourceCsmScore: undefined,
          remark: ''
        },
        rules: {
          targetCsmPhone: [{ required: true, message: '请输入客户电话', trigger: 'change' }],
          sourceCsmPhone: [{ required: true, message: '请输入被合并客户电话', trigger: 'change' }],
          score: [{ required: true, message: '请输入合并积分', trigger: 'change' }],
          remark: [{ required: true, message: '请输入备注信息', trigger: 'change' }]
        },
        sourceCsmList: [], // 被合并用户数据
        targetCsmList: [], // 主账号数据
        sourceCsmRowsSelected: [], // 主账号选择行
        targetCsmRowsSelected: [], // 被合并账号选择行
        data1: {
          phoneItems: [],
          addressItems: []
        }, // 主账号展开行数据
        data2: {
          phoneItems: [],
          addressItems: []
        } // 被合并账号展开行数据
      }
    },
    computed: {
      column1: function() {
        return [
          {
            type: 'expand',
            render: (h, props) => {
              return (
                <div class='expand-table-wrapper'>
                  <table>
                    <tr>
                      <th>常用电话</th>
                    </tr>
                    {this.data1.phoneItems && this.data1.phoneItems.length > 0 && this.data1.phoneItems.map(item => (
                      <tr>
                        <td>
                          {item.cpStatus && (item.cpStatus !== -1 && item.cpStatus !== -2) &&
                          <span>{item.csmPhone}({item.contact})</span>}
                          {item.cpStatus && (item.cpStatus === -1 || item.cpStatus === -2) &&
                          <span>{item.csmPhone}({item.contact})<span class='dangerColor'>(已注销)</span></span>}
                        </td>
                      </tr>
                    ))}
                  </table>
                  <table>
                    <tr>
                      <th>所属机构</th>
                      <th>常用地址</th>
                      <th>最后安检时间</th>
                      <th> </th>
                    </tr>
                    {this.data1.addressItems && this.data1.addressItems.map(x => (
                      <tr>
                        <td>{x.orgName}</td>
                        <td>{x.provinceName}{x.cityName}{x.countryName}{x.streetName}{x.csmAddress}</td>
                        <td>{moment(x.lastSCheckDt).format('YYYY-MM-DD HH:mm:ss')}</td>
                        {x.insureCode && x.insureEndDt && <td>
                          保单号：{x.insureCode}&emsp;保险到期时间：{x.insureEndDt && moment(x.insureEndDt).valueOf() > moment('2000-01-01').valueOf() ? moment(x.insureEndDt).format('YYYY-MM-DD HH:mm:ss') : '' }
                        </td>}
                      </tr>
                    ))}
                  </table>
                </div>
              )
            }
          },
          {
            type: 'selection'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110
          },
          {
            prop: 'csmName',
            label: '名称',
            width: 110
          },
          {
            prop: 'csmType',
            label: '类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.csmTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'csmQuality',
            label: '客户性质',
            render: (h, { row }) => {
              if (row.csmQuality === 1) {
                return <span>普通</span>
              } else if (row.csmQuality === 2) {
                return <span>特殊</span>
              } else if (row.csmQuality === 3) {
                return <span>白金</span>
              } else {
                return <span>钻石</span>
              }
            }
          },
          {
            prop: 'newFrom',
            width: 120,
            label: '客户来源',
            render: (h, { row }) => <span>{ newFromMap[row.newFrom] || '户外广告' }</span>
          },
          {
            prop: 'deposit',
            label: '押金',
            align: 'right'
          },
          {
            prop: 'csmRgPhone',
            label: '电话',
            width: 110
          },
          {
            prop: 'csmRgAddress',
            label: '地址',
            width: 180
          },
          {
            prop: 'totalGasCount',
            label: '使用瓶数',
            align: 'right'
          },
          {
            prop: 'score',
            label: '积分',
            align: 'right',
            render: (h, { row }) => <span class='dangerColor'>{ row.score }</span>
          },
          {
            prop: 'salesmanName',
            label: '销售人员'
          },
          {
            prop: 'lastSCheckDt',
            label: '最后安检时间',
            width: '160',
            render: (h, { row }) => <span>{ row.lastSCheckDt && parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'csmStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.csmStatus && formatColumnMap(this.csmStatusMap, 'value', row.csmStatus, 'desc') }</span>
          },
          {
            prop: 'createTime',
            label: '开户时间',
            width: '160',
            render: (h, { row }) => <span>{ parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'remark',
            width: 150,
            label: '备注'
          }
        ]
      },
      column2: function() {
        return [
          {
            type: 'expand',
            render: (h, props) => {
              return (
                <div class='expand-table-wrapper'>
                  <table>
                    <tr>
                      <th>常用电话</th>
                    </tr>
                    {this.data2.phoneItems && this.data2.phoneItems.length > 0 && this.data2.phoneItems.map(item => (
                      <tr>
                        <td>
                          {item.cpStatus && (item.cpStatus !== -1 && item.cpStatus !== -2) &&
                          <span>{item.csmPhone}({item.contact})</span>}
                          {item.cpStatus && (item.cpStatus === -1 || item.cpStatus === -2) &&
                          <span>{item.csmPhone}({item.contact})<span class='dangerColor'>(已注销)</span></span>}
                        </td>
                      </tr>
                    ))}
                  </table>
                  <table>
                    <tr>
                      <th>所属机构</th>
                      <th>常用地址</th>
                      <th>最后安检时间</th>
                      <th> </th>
                    </tr>
                    {this.data2.addressItems && this.data2.addressItems.map(x => (
                      <tr>
                        <td>{x.orgName}</td>
                        <td>{x.provinceName}{x.cityName}{x.countryName}{x.streetName}{x.csmAddress}</td>
                        <td>{moment(x.lastSCheckDt).format('YYYY-MM-DD HH:mm:ss')}</td>
                        {x.insureCode && x.insureEndDt && <td>
                          保单号：{x.insureCode}&emsp;保险到期时间：{x.insureEndDt && moment(x.insureEndDt).valueOf() > moment('2000-01-01').valueOf() ? moment(x.insureEndDt).format('YYYY-MM-DD HH:mm:ss') : '' }
                        </td>}
                      </tr>
                    ))}
                  </table>
                </div>
              )
            }
          },
          {
            type: 'selection'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110
          },
          {
            prop: 'csmName',
            label: '名称',
            width: 110
          },
          {
            prop: 'csmType',
            label: '类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.csmTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'csmQuality',
            label: '客户性质',
            render: (h, { row }) => {
              if (row.csmQuality === 1) {
                return <span>普通</span>
              } else if (row.csmQuality === 2) {
                return <span>特殊</span>
              } else if (row.csmQuality === 3) {
                return <span>白金</span>
              } else {
                return <span>钻石</span>
              }
            }
          },
          {
            prop: 'newFrom',
            width: 120,
            label: '客户来源',
            render: (h, { row }) => <span>{ newFromMap[row.newFrom] || '户外广告' }</span>
          },
          {
            prop: 'deposit',
            label: '押金',
            align: 'right'
          },
          {
            prop: 'csmRgPhone',
            label: '电话',
            width: 110
          },
          {
            prop: 'csmRgAddress',
            label: '地址',
            width: 180
          },
          {
            prop: 'totalGasCount',
            label: '使用瓶数',
            align: 'right'
          },
          {
            prop: 'score',
            label: '积分',
            align: 'right',
            render: (h, { row }) => <span class='dangerColor'>{ row.score }</span>
          },
          {
            prop: 'salesmanName',
            label: '销售人员'
          },
          {
            prop: 'lastSCheckDt',
            label: '最后安检时间',
            width: '160',
            render: (h, { row }) => <span>{ row.lastSCheckDt && parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'csmStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.csmStatus && formatColumnMap(this.csmStatusMap, 'value', row.csmStatus, 'desc') }</span>
          },
          {
            prop: 'createTime',
            label: '开户时间',
            width: '160',
            render: (h, { row }) => <span>{ parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'remark',
            width: 150,
            label: '备注'
          }
        ]
      }
    },
    methods: {
      open() {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      searchCsm() {
        const { targetCsmPhone, sourceCsmPhone } = this.temp
        if (targetCsmPhone && sourceCsmPhone) {
          // 执行校验成功的相关操作
          const params = {
            sourceCsmPhone: this.temp.sourceCsmPhone,
            targetCsmPhone: this.temp.targetCsmPhone
          }
          this.queryCsm(params)
        } else {
          this.$refs['dataForm'].validateField(['targetCsmPhone', 'sourceCsmPhone'])
        }
      },
      async queryCsm(params) {
        const res = await queryCsmByPhone(params)
        this.sourceCsmList = res.data.sourceCsmList
        this.targetCsmList = res.data.targetCsmList
      },
      // 查询客户详情（展开行时用）
      async queryCsmDetail(csmRgPhone, type) {
        const res = await mergeAsyncFunc(queryCsmInfo, { csmRgPhone })
        this[`data${type}`] = res.data
        if (this[`data${type}`] && this[`data${type}`].phoneItems.length > 0) {
          const index = this[`data${type}`].phoneItems.findIndex(item => item.isMain === 1)
          const item = this[`data${type}`].phoneItems.find(item => item.isMain === 1)
          this[`data${type}`].phoneItems.splice(index, 1)
          this[`data${type}`].phoneItems.unshift(item)
        }
        if (this[`data${type}`] && this[`data${type}`].addressItems.length > 0) {
          const index = this[`data${type}`].addressItems.findIndex(item => item.isMain === 1)
          const item = this[`data${type}`].addressItems.find(item => item.isMain === 1)
          this[`data${type}`].addressItems.splice(index, 1)
          this[`data${type}`].addressItems.unshift(item)
        }
      },
      merge() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (this.sourceCsmRowsSelected.length === 0 || this.targetCsmRowsSelected.length === 0) {
            this.$message.error('请选择主账号客户和被合并客户进行积分合并')
            return
          }
          if (this.temp.sourceCsmScore === 0) {
            this.$message.error('被合并客户积分为0,无需合并')
            return
          }
          if (!this.temp.score || this.temp.score <= 0) {
            this.$message.error('请输入正确的合并积分')
            return
          }
          if (parseInt(this.temp.score) > parseInt(this.temp.sourceCsmScore)) {
            this.$message.error('合并积分必须小于可合并积分')
            return
          }
          const params = {
            sourceCsmId: this.sourceCsmRowsSelected[0].csmId || 0,
            sourceCsmCode: this.sourceCsmRowsSelected[0].csmCode,
            sourceCsmName: this.sourceCsmRowsSelected[0].csmName,
            sourceCsmPhone: this.sourceCsmRowsSelected[0].csmRgPhone,
            score: this.temp.score,
            targetCsmId: this.targetCsmRowsSelected[0].csmId || 0,
            targetCsmCode: this.targetCsmRowsSelected[0].csmCode,
            targetCsmName: this.targetCsmRowsSelected[0].csmName,
            targetCsmPhone: this.targetCsmRowsSelected[0].csmRgPhone,
            remark: this.temp.remark
          }
          if (!params.sourceCsmId || params.sourceCsmId === 0) {
            this.$message.error('没有查询到被合并客户信息')
            return
          }
          if (!params.targetCsmId || params.targetCsmId === 0) {
            this.$message.error('没有查询到主账号客户信息')
            return
          }
          if (params.sourceCsmId === params.targetCsmId) {
            this.$message.error('两个电话对应同一个客户账号无法合并')
            return
          }
          if (this.sourceCsmRowsSelected[0].score === 0) {
            this.$message.error(`被合并客户【${params.sourceCsmName}-${params.sourceCsmPhone}】积分余额为0,无需合并`)
            return
          }
          this.$confirm(`确认将【${params.sourceCsmName}-${params.sourceCsmPhone}】账户的积分合并到【${params.targetCsmName}-${params.targetCsmPhone}】账户?`, '提示', {
            type: 'warning'
          }).then(() => {
            this.submit(params)
          })
        })
      },
      async submit(params) {
        await mergeScore(params)
        this.searchCsm()
        this.$notify({
          title: '提示',
          message: '积分合并成功',
          type: 'success',
          duration: 2000
        })
      },
      // 主账号客户点击事件
      handleCurrentChangeOne(val) {
        this.targetCsmRowsSelected = val
        this.$set(this.temp, 'targetCsmName', val[0].csmName)
      },
      // 被合并客户点击时间
      handleCurrentChangeTwo(val) {
        this.sourceCsmRowsSelected = val
        this.$set(this.temp, 'sourceCsmName', val[0].csmName)
        this.$set(this.temp, 'sourceCsmScore', val[0].score)
        this.$set(this.temp, 'score', val[0].score)
      },
      toggleSelection(row) {
        this.$refs['lbTableMain'].toggleRowSelection(row)
      },
      toggleSelection2(row) {
        this.$refs['lbTable'].toggleRowSelection(row)
      },
      // 展开行
      async clickExpand(row, expandedRows, type) {
        if (expandedRows.length > 0) {
          this[`data${type}`] = {}
          await this.queryCsmDetail(row.csmRgPhone, type)
        }
      },
      reset() {
        this.temp = {
          targetCsmPhone: '',
          sourceCsmPhone: '',
          targetCsmName: '',
          sourceCsmName: '',
          score: undefined,
          sourceCsmScore: undefined,
          remark: ''
        }
        this.sourceCsmList = []
        this.targetCsmList = []
        this.sourceCsmRowsSelected = []
        this.targetCsmRowsSelected = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
  .tip {
    p {
      line-height: 26px;
    }
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 20px;
  margin-bottom: 10px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
/deep/ .el-table {
  .expand-table-wrapper {
    display: flex;
    align-items: baseline;
    table {
      th,
      td {
        padding: 5px 10px;
      }
    }
  }
}
</style>
